//分页
function getPageData(rule) {
  let data = rule.data //总数据
  let pageData = [] //分页返回数据
  let pageIndex = rule.pageIndex - 1
  let pageSize = rule.pageSize
  let count = 0
  for (let i = 0; i < data.length; i++) {
    if (data[i + pageIndex * pageSize]) {
      pageData.push(data[i + pageIndex * pageSize])
      count++
    } else {
      break
    }
    if (count > pageSize - 1) {
      break
    }
  }
  return pageData
}

//验证必填项
function checkUpdateData(data, ignore = []) {
  let bool = true
  for (let key in data) {
    if (ignore.indexOf(key) === -1) {
      if (Array.prototype.isPrototypeOf(data[key])) {
        if (data[key].length === 0) bool = false
        break
      }
      if (typeof data[key] === 'string') {
        if (!data[key]) {
          bool = false
          break
        }
      }
    }
  }
  return bool
}

// 将base64转换为file
function dataURLtoFile(dataurl, filename = 'file') {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let suffix = mime.split('/')[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime
  })
}

//获取路由某一项参数,
function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) return decodeURI(r[2])
  return null
}

//科学计数法转十进制
function toNonExponential(num) {
  var m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/)
  return num.toFixed(Math.max(0, (m[1] || '').length - m[2]))
}

//  axios添加jsonp请求

function addJsonP(url, options) {
  if (!url) {
    return
  }
  // 回调函数名称
  let index = parseInt(Math.random() * 99)
  let callbackName = 'cb' + index
  // 装载参数
  url = url + (/\?/.test(url) ? '&' : '?')
  options.params &&
    Object.keys(options.params).forEach(key => {
      url += `${key}=${options.params[key]}&`
    })
  url += `callback=${callbackName}`
  return new Promise(resolve => {
    let JSONP = document.createElement('script')
    JSONP.type = 'text/javascript'
    JSONP.src = url

    window[callbackName] = res => {
      if (res.status === 0) {
        //解决新老版本地区code不同问题
        let code = res.result.addressComponent.adcode
        if (code === '511503') {
          res.result.addressComponent.adcode = '511522'
        }
        if (code === '511504') {
          res.result.addressComponent.adcode = '511521'
        }
        resolve(
          Object.assign(res.result, {
            code: 0,
            message: '请求成功'
          })
        )
      } else {
        resolve({ code: 500, message: '服务器错误' })
      }
    }

    document.getElementsByTagName('head')[0].appendChild(JSONP)

    setTimeout(() => {
      document.getElementsByTagName('head')[0].removeChild(JSONP)
      delete window[callbackName]
    }, 500)
  })
}

function fixVideo() {
  setTimeout(() => {
    let domArr = document.querySelectorAll('video')
    for (let i = 0; i < domArr.length; i++) {
      domArr[i].removeAttribute('x5-playsinline')
    }
  }, 10)
}
function colorExcessive(value, colorList) {
  let color1 = 0,
    color2 = 0,
    color3 = 0,
    level1 = 0,
    level2 = 0,
    level3 = 0
  if (!colorList || colorList.length === 0) {
    //蓝 （68,130,229）0
    //绿（33,214,156）50
    //黄（244,207,54）100
    //红（236,58,58）150
    colorList = [
      {
        color: 'rgb(68, 130, 229)',
        value: 0
      },
      {
        color: 'rgb(33, 214, 156)',
        value: 50
      },
      {
        color: 'rgb(244, 207, 54)',
        value: 100
      },
      {
        color: 'rgb(236, 58, 58)',
        value: 150
      }
    ]
  }

  //value大于最大值
  color1 = decomposeColor(colorList[colorList.length - 1].color)[0]
  color2 = decomposeColor(colorList[colorList.length - 1].color)[1]
  color3 = decomposeColor(colorList[colorList.length - 1].color)[2]
  let colorEnd = 0,
    colorStart = 0
  for (let i = 0; i < colorList.length; i++) {
    if (value <= colorList[i].value) {
      //value小于最小值
      if (i === 0) {
        color1 = decomposeColor(colorList[0].color)[0]
        color2 = decomposeColor(colorList[0].color)[1]
        color3 = decomposeColor(colorList[0].color)[2]
        break
      }

      colorEnd = decomposeColor(colorList[i].color)
      colorStart = decomposeColor(colorList[i - 1].color)
      level1 = (colorEnd[0] - colorStart[0]) / (colorList[i].value - colorList[i - 1].value)
      level2 = (colorEnd[1] - colorStart[1]) / (colorList[i].value - colorList[i - 1].value)
      level3 = (colorEnd[2] - colorStart[2]) / (colorList[i].value - colorList[i - 1].value)
      color1 = parseInt(colorStart[0] + (value - colorList[i - 1].value) * level1)
      color2 = parseInt(colorStart[1] + (value - colorList[i - 1].value) * level2)
      color3 = parseInt(colorStart[2] + (value - colorList[i - 1].value) * level3)
      break
    }
  }
  function decomposeColor(color) {
    var regexp = /[0-9]{0,3}/g
    //利用正则表达式去掉多余的部分，将rgb中的数字提取
    var colorArr = color.match(regexp).filter(s => {
      return s && s.trim()
    })
    for (let i = 0; i < colorArr.length; i++) {
      colorArr[i] = parseInt(colorArr[i])
    }
    return colorArr
  }
  return `rgb(${color1},${color2},${color3})`
}

export {
  checkUpdateData,
  getPageData,
  dataURLtoFile,
  getQueryString,
  toNonExponential,
  addJsonP,
  fixVideo,
  colorExcessive
}
